import axios from 'axios';
import { ElMessage } from 'element-plus';

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE_HREF + process.env.VUE_APP_BASE_API,
    timeout: 5000
});

service.interceptors.request.use(config => {
    if (!['/user/login', '/user/register'].includes(config.url)) {
        const token = localStorage.getItem('token');
        if (token) {
            config.headers.Authorization = `Bearer ${token}`;
        }
    }
    return config;
}, error => {
    return Promise.reject(error);
});

service.interceptors.response.use(response => {
    return response.data;
}, error => {
    if (error.response?.status === 401) {
        localStorage.removeItem('token');
        window.location.reload();
    }
    ElMessage.error(error.response?.data?.message || '请求失败');
    return Promise.reject(error);
});

export default service;